//
//  CouponListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/8/24.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "MyCouponListCell.h"

#import "CouponListViewController.h"

@interface CouponListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*dataArray;

@end

@implementation CouponListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_myCoupon];
}

- (void)refreshParam {
    self.pageNum = 1;
    self.pageSize = 20;
}

- (void)initView {
    
    self.title = @"领取优惠券";
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.dataArray[indexPath.row].itemHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
        if (isLogin) {
            [weakSelf request_getCouponWith:self.dataArray[indexPath.row].scoId];
        }
    }];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyCouponListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCouponListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"MyCouponListCell" bundle:nil] forCellReuseIdentifier:@"MyCouponListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_myCoupon];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_myCoupon];
        }];
        
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (NSMutableArray<CommonCouponModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_myCoupon {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [t setValue:[TTUserModel sharedObject].cityName forKey:@"scoCity"];
    [t setValue:@"1" forKey:@"scoCouponType"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CouponList];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在获取优惠券列表"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                    }
                    
                    for (int i=0; i < list.count; i++) {
                        NSDictionary *sysCouponListDic = list[i];
                        CommonCouponModel *couponModel = [CommonCouponModel modelWithDictionary:sysCouponListDic];
                        couponModel.itemHeight = (TTScreenWidth - 30)/3.19 + 20;
                        couponModel.couponType = 4;
                        [weakSelf.dataArray addObject:couponModel];
                    }
                    
                    if (weakSelf.dataArray.count == 0) {
                        
                        if (weakSelf.tableview) {
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoCoupon btnTitle:@"" didPressButton:^{}];
                        }
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
}

- (void)request_getCouponWith:(NSString *)scoId {
    
    [[BA_BusinessHelper shared] callgetCouponWith:scoId And:@"" comption:^(BOOL success) {

        if (success) {
            [SVProgressHUD showSuccessWithStatus:@"领取成功"];
            [SVProgressHUD dismissWithDelay:1];
        }

    }];
}

@end
